﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ROrganizer.Client
{
    public class HashRepository
    {
        public HashEntry[] All()
        {
            using (ApplicationData.OpenSession(ApplicationData.HashRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.HashRepository);
                var serializer = new HashSerializer();

                var query = from entry in serializer.Deserialize(document)
                            where entry.FileTimestamp == HashRepository.GetFileStamp(entry.File)
                            select entry;

                return query.ToArray();
            }
        }

        public HashEntry Get(string filename)
        {
            using (ApplicationData.OpenSession(ApplicationData.HashRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.HashRepository);
                var serializer = new HashSerializer();
                var entry = serializer.Deserialize(document, filename.ToLower());

                if (entry != null && entry.FileTimestamp == HashRepository.GetFileStamp(entry.File))
                    return entry;

                return null;
            }
        }

        public void SaveOrUpdate(params HashEntry[] entries)
        {
            using (ApplicationData.OpenSession(ApplicationData.HashRepository))
            {
                var document = ApplicationData.GetDocument(ApplicationData.HashRepository);
                var serializer = new HashSerializer();

                serializer.Update(document, entries);
                ApplicationData.UpdateDocument(ApplicationData.HashRepository, document);
            }
        }

        private static DateTime GetFileStamp(string path)
        {
            if (!File.Exists(path))
                return DateTime.MinValue;

            return new FileInfo(path).LastWriteTimeUtc.ToUniversalTime();
        }
    }
}
